package com.baizhi;

import com.baizhi.entity.Product;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
public class RestHighLevelClientForObject {

    private final RestHighLevelClient restHighLevelClient;

    @Autowired
    public RestHighLevelClientForObject(RestHighLevelClient restHighLevelClient) {
        this.restHighLevelClient = restHighLevelClient;
    }

    /**
     * 将对象放入ES中
     */
    @Test
    public void testIndex() throws IOException {
        Product product = new Product();
        product.setId(3);
        product.setTitle("三只松鼠");
        product.setPrice(6.8);
        product.setDescription("三只松鼠坚果超好吃！");

        // 录入es中
        IndexRequest indexRequest = new IndexRequest("products");
        indexRequest.id(product.getId().toString())
                .source(new ObjectMapper().writeValueAsString(product), XContentType.JSON);
        IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(indexResponse.status());
    }

    /**
     * 从ES中取出对象
     */
    @Test
    public void testSearch() throws IOException {
        SearchRequest searchRequest = new SearchRequest("products");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchAllQuery())
                .from(0)
                .size(10);
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        System.out.println("总条数：" + searchResponse.getHits().getTotalHits().value);
        System.out.println("最大得分：" + searchResponse.getHits().getMaxScore());

        List<Product> productList = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Product product = new ObjectMapper().readValue(hit.getSourceAsString(), Product.class);
            productList.add(product);
        }

        // 遍历集合
        for (Product product : productList) {
            System.out.println(product);
        }
    }
}
